package com.otod.commons.utils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * MAP相关工具类
 *
 * @author jqiu
 */
public class MapUtil {
	 private static Logger logger = LoggerFactory.getLogger(MapUtil.class);
	  
    /**
     * 将map集合转换成Bean集合，Bean的属性名与map的key值对应时不区分大小写
     *
     * @param List<E>   目标
     * @param List<Map> 源
     * @return
     */
    public static <E> List<E> toBeanList(Class<E> cla, List<Map<String, Object>> mapList) {
        List<E> list = new ArrayList<E>(mapList.size());
        for (Map<String, Object> map : mapList) {
            E obj = toBean(cla, map);
            list.add(obj);
        }
        return list;
    }

    /**
     * 将map转换成Bean，Bean的属性名与map的key值对应时不区分大小写
     *
     * @param E   目标
     * @param Map 源
     * @return
     */
    public static <E> E toBean(Class<E> cla, Map<String, Object> map) {
        E obj = null;
        try {
            obj = cla.newInstance();
            if (obj == null) {
                throw new Exception();
            }
        } catch (Exception e) {
            logger.error("类型实例化对象失败,类型:" + cla,e);
            return null;
        }


        Method[] ms = cla.getMethods();
        String tempName;
        Object valueObj;
        for (Method method : ms) {
            String mname = method.getName().toLowerCase();
            if (mname.startsWith("set")) {
                Class[] paramArray = method.getParameterTypes();
                //公有一个参数时才处理
                if(paramArray.length != 1){							
                	continue;
                }
                
                tempName = mname.substring(3);
                tempName = tempName.substring(0,1).toLowerCase()+tempName.substring(1);
                valueObj = map.get(tempName);
                if(valueObj == null){
                	valueObj = map.get(tempName.toUpperCase());
                }
                //map中值不为空时才继续
                if(valueObj == null){
                	continue;
                }
                
                //如果类型不匹配则不处理
                if(!valueObj.getClass().getName().equals(paramArray[0].getName())){
                	continue;
                }
                
                try {
                    method.invoke(obj, valueObj);
                } catch (Exception e) {
                    logger.error("属性值装入失败,装入方法：" + cla.getName() + "."
                            + method.getName(),e);
                }
            }
        }
        return obj;
    }
}
